s<template>
    <div>
        <Form ref="form1" :model="form1" :label-width="120">
        <div v-if="!switchFlag">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                  <FormItem label="二级集团：">
                    <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
                  </FormItem>
                </i-col>
                <i-col span="8">
                  <FormItem label="企业名称：" prop="companyName">
                    <company-select v-model="form1.companyName"></company-select>
                  </FormItem>
                </i-col>
                <i-col span="8">
                    <div style="float: right;">
                        <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                        <Button @click="reset" class="ivu-btn-reset" style="margin-left: 10px" >重置</Button>
                        <Button @click="switchQuery(true)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                    </div>
                </i-col>
            </Row>
        </div>
        <div v-else>
            <Row class="query-form" :gutter="16">
              <i-col span="8">
                <FormItem label="二级集团：">
                  <two-level-org org-code v-model="form1.twoLevelOrgId" ></two-level-org>
                </FormItem>
              </i-col>
              <i-col span="8">
                <FormItem label="企业名称：" prop="companyName">
                  <company-select v-model="form1.companyName"></company-select>
                </FormItem>
              </i-col>
                <i-col span="8">
                    <FormItem label="计划名称：">
                        <Input type="text" v-model="form1.planName"/>
                    </FormItem>
                </i-col>
            </Row>
            <Row class="query-form2" :gutter="16">
              <i-col span="8">
                <FormItem label="排查部门：" prop="screenOrgId">
                  <cascaderDom ref="existOrg" @setOrgInfo="setOrgInfo" :orgTree="true" :rootOrgId="rootOrgId"></cascaderDom>
                </FormItem>
              </i-col>
              <i-col span="8">
                <FormItem label="排查岗位：" prop="screenPositionName">
                  <Input type="text" v-model="form1.screenPositionName"/>
                </FormItem>
              </i-col>
                <i-col span="8">
                    <FormItem label="排查频率：" prop="checkCycle">
                        <Select  v-model="form1.checkCycle">
                            <Option value="2" checked>每天</Option>
                            <Option value="3">工作日</Option>
                            <Option value="8">双周</Option>
                            <Option value="6">月度</Option>
                            <Option value="7">季度</Option>
                            <Option value="4">半年</Option>
                            <Option value="1">年度</Option>
                            <Option value="5">自定义</Option>
                        </Select>
                    </FormItem>
                </i-col>
            </Row>
            <Row class="query-form2" :gutter="16">
              <i-col span="24">
                <div style="float: right;">
                  <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                  <Button @click="reset" class="ivu-btn-reset" style="margin-left: 10px">重置</Button>
                  <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                </div>
              </i-col>
            </Row>
        </div>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <Button size="large" class="ivu-btn-add" icon="md-cloud-download" @click="exportFile">导出</Button>
                    <Button size="large" type="success" class="ivu-btn-add" @click="multiModify">批量修改</Button>
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="delayInfo" v-if="ifHoliday">延期一年</Button>
                    <Button size="large" class="ivu-btn-add" icon="ios-trash" @click="batchDelete">删除</Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :loading="loading" size="small" :height="tableHeight" class="table" no-data-text="没有查询到相关数据!" @on-sort-change="querySort"
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>

        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="modalTitle" :transfer=false v-model="model1" :width=900 class-name='limit-height-dialog'>
            <Form ref="dataForm" :model="dataForm" label-position="top" :rules="ruleCustom">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="排查岗位：" prop="screenPositionId">
                            <Input type="text" readonly @on-focus="openModelModal" v-model="dataForm.screenPositionName"></Input>
                            <Input type="text" v-show="false" v-model="dataForm.screenPositionId"></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="计划名称：" prop="planName">
                            <Input type="text" v-model="dataForm.planName"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="计划日期范围：" prop="startDate">
                            <DatePicker v-model="planDate" type="datetimerange" :editable="false"
                            style="width: 100%" format="yyyy-MM-dd"   :options="startDateOption"
                            placeholder="请选择计划时间（开始，结束）"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="任务派发类型：">
                            <RadioGroup v-model="dataForm.distributeType">
                                <Radio label="0">按岗位派发任务</Radio>
                                <Radio label="1">按人员派发任务</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="是否共享任务：（选择“是”表示只有一人可执行任务；选择“否”表示多人需分别执行任务）" prop="planType">
                            <RadioGroup v-model="dataForm.planType" :disabled="planTypeEnable">
                                <Radio label="0">是</Radio>
                                <Radio label="1">否</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="重复类型：" prop="checkCycle">
                            <div style="display:flex;flex-direction:row">
                                <div style="display:flex;flex-direction:column">
                                    <RadioGroup @on-change="cycleChange" v-model="viewCheckCycleRadio">
                                        <Radio label="2" checked>每天</Radio>
                                        <Radio label="3">工作日</Radio>
                                        <Radio label="8">双周</Radio>
                                        <Radio label="6">月度</Radio>
                                        <Radio label="7">季度</Radio>
                                        <Radio label="4">半年</Radio>
                                        <Radio label="1">年度</Radio>
                                        <Radio label="5">自定义</Radio>
                                    </RadioGroup>
                                    <span v-show='viewSpanShow'>
                                        <CheckboxGroup v-model="viewCheckCycleCheckbox">
                                            <Checkbox label="51">周一</Checkbox>
                                            <Checkbox label="52">周二</Checkbox>
                                            <Checkbox label="53">周三</Checkbox>
                                            <Checkbox label="54">周四</Checkbox>
                                            <Checkbox label="55">周五</Checkbox>
                                            <Checkbox label="56">周六</Checkbox>
                                            <Checkbox label="57">周日</Checkbox>
                                        </CheckboxGroup>
                                    </span>
                                </div>
                                <div style="display:flex;flex-direction:column">
                                    <span style="margin-left: 10px">单次任务有效期天数：<Input :disabled="lastDaysDisabled"
                                                                            style="width: 100px" type="number"
                                                                            v-model="dataForm.lastDays"/></span>
                                    <label style="margin-left: 10px;color:red">{{lastDayLabel}}</label>
                                </div>
                            </div>
                        </FormItem>
                    </Col>
                </Row>
                <Row v-show="dataForm.distributeType == '1'" type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="排查人员：（添加排查人员后，将不再按岗位派发任务，而改为直接给所选人员派发任务）" prop="screenUserIds">
                            <div style="display:flex">
                                <Select multiple v-model="screenUserIds" placeholder="">
                                    <Option v-for="item in screenUsers" :value="item.userId" :key="item.userId">{{item.userName}}</Option>
                                </Select>
                                <Button type="primary" style="margin:0" class='ivu-btn-save' @click="choosePeople">选择</Button>
                            </div>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveData()">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancel" style="margin-left: 2px">取消</Button>
            </div>
        </Modal>
        <Modal title="计划查看" :transfer=false v-model="viewModal" class="modal-view-detail" :width=800>
            <Form ref="viewForm" :model="viewForm" :label-width="120">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="排查岗位：" prop="checkLevel">
                            {{viewForm.screenPositionName}}
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="计划名称：">
                            {{viewForm.planName}}
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="创建人：" prop="checkLevel">
                            {{viewForm.createUserName}}
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="创建时间：">
                            {{viewForm.createDateStr}}
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="计划时间范围：">
                            {{viewForm.startDate}}-{{viewForm.endDate}}
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="任务派发类型：">
                            <RadioGroup v-model="viewForm.distributeType">
                                <Radio label="0" disabled>按岗位派发任务</Radio>
                                <Radio label="1" disabled>按人员派发任务</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="是否共享任务：">
                            <RadioGroup v-model="viewForm.planType" >
                                <Radio label="0" disabled>是</Radio>
                                <Radio label="1" disabled>否</Radio>
                            </RadioGroup>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="重复类型：">
                            <RadioGroup v-model="viewCheckCycleRadio">
                                <Radio label="2" disabled>每天</Radio>
                                <Radio label="3" disabled>工作日</Radio>
                                <Radio label="8" disabled>双周</Radio>
                                <Radio label="6" disabled>月度</Radio>
                                <Radio label="7" disabled>季度</Radio>
                                <Radio label="4" disabled>半年</Radio>
                                <Radio label="1" disabled>年度</Radio>
                                <Radio label="5" disabled>自定义</Radio>
                            </RadioGroup>
                            <span style="margin-left: 10px">单次任务有效期天数：{{viewForm.lastDays}}</span>
                            <span v-show='viewSpanShow'><br>
                                    <CheckboxGroup v-model="viewCheckCycleCheckbox">
                                        <Checkbox label="51" disabled>周一</Checkbox>
                                        <Checkbox label="52" disabled>周二</Checkbox>
                                        <Checkbox label="53" disabled>周三</Checkbox>
                                        <Checkbox label="54" disabled>周四</Checkbox>
                                        <Checkbox label="55" disabled>周五</Checkbox>
                                        <Checkbox label="56" disabled>周六</Checkbox>
                                        <Checkbox label="57" disabled>周日</Checkbox>
                                    </CheckboxGroup>
                                 </span>
                        </FormItem>
                    </Col>
                </Row>
                <Row type="flex" v-show="viewForm.distributeType == '1'" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem label="排查人员：" prop="screenUserName">
                            {{viewForm.screenUserName}}
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="viewModal=false">关闭</Button>
            </div>
        </Modal>

      <Modal title="批量修改" :transfer=false v-model="model3" :width=900 class-name='limit-height-dialog'>
        <Form ref="dataForm" label-position="top" :rules="ruleCustom">
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="20">
              <FormItem label="计划日期范围：" prop="startDate">
                <DatePicker v-model="planDate" type="datetimerange"  :transfer="true"
                            style="width: 100%" format="yyyy-MM-dd"   :options="startDateOption"
                            placeholder="请选择计划时间（开始，结束）"></DatePicker>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="saveMultiModify()">确定</Button>
          <Button type="primary" class='ivu-btn-cancel' @click="handleCanleMultiModify" style="margin-left: 2px">取消</Button>
        </div>
      </Modal>

        <apsgPlanUserSelect ref="apsgPlanUserSelect" @closeModel="closeModel" @getSelectData="getSelectData" :userForSelectModal="apsgPlanUserForSelectModal" :orgId="companyId">
        </apsgPlanUserSelect>

        <Modal :transfer=false footer-hide v-model="selectModelModal" :width=900>
            <ApsgItemPlanForSelect @getSelectModelData="getSelectModelData"></ApsgItemPlanForSelect>
        </Modal>

    </div>
</template>

<script>
    import {Api} from '../../../api/index.js'
    import cascaderPosition from '../../../components/cascader-position'
    import cascaderDom from '../../../components/cascader-dom'
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import ApsgItemPlanForSelect from './apsgItemPlanForSelect.vue'
    import ApsgPlanUserSelect from './apsgPlanUserSelect.vue'

    export default {
        components: {
            cascaderPosition,cascaderDom,ApsgItemPlanForSelect,ApsgPlanUserSelect
        },
        data() {
            return {
                multiModifyPlanIds:"",
                planDate:[],
                planTypeEnable: false,
                lastDayLabel:"",
                model4: false,
                rootOrgId:'',
                currentUserId:"",
                loginId:"",
                modalTitle:"",
                form1: {planName:"",screenPositionId:'',screenOrgId:'',checkCycle:''},
                switchFlag: false,
                apsgPlanUserForSelectModal:false,
                companyId:"",
                dataForm: {},
                startDateOption:{
                    disabledDate(date) {
                        return (date && date.valueOf() < Date.now() - 86400000) || new Date(new Date().getFullYear() + '-12-31').valueOf() <  date.valueOf();
                    }

                },
                //分页参数
                pageSizeArray: [10, 20, 50,100, 200, 500],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        type: 'selection',
                        // render: (h, params) => {
                        //     return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        // }
                    },
                    {
                        minWidth: 220,
                        title: '计划名称',
                        key: 'planName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '计划开始日期',
                        key: 'startDate',
                        align: 'center',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('span', this.formatDate(new Date(params.row.startDate),"yyyy-MM-dd"));
                        }
                    },
                    {
                        minWidth: 130,
                        title: '计划结束日期',
                        key: 'endDate',
                        align: 'center',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('span', this.formatDate(new Date(params.row.endDate),"yyyy-MM-dd"));
                        }
                    },
                    {
                        minWidth: 130,
                        title: '频率',
                        key: 'checkCycle',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.checkCycle == '1') {
                                return h('span',  '年度')
                            } else if (params.row.checkCycle == '2') {
                                return h('span',  '每天')
                            } else if (params.row.checkCycle == '3') {
                                return h('span',  '工作日')
                            }  else if (params.row.checkCycle == '8') {
                                return h('span',  '双周')
                            }  else if (params.row.checkCycle[0] == '5') {
                                return h('span',  '自定义')
                            } else if (params.row.checkCycle == '6') {
                                return h('span',  '月度')
                            } else if (params.row.checkCycle == '7') {
                                return h('span',  '季度')
                            } else if (params.row.checkCycle == '4') {
                                return h('span',  '半年')
                            }
                        }
                    },
                    {
                        minWidth: 230,
                        title: '排查公司',
                        key: 'screenOrgName',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '排查岗位',
                        key: 'screenPositionName',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (this.currentUserId != params.row.createUserId&&this.loginId != this.Common.admin)  && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                            && (sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined) ? '#d0d0d0':'',
                                        pointerEvents:  (this.currentUserId != params.row.createUserId &&this.loginId != this.Common.admin)  && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                        &&(sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined) ? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.toEdit(params);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (this.currentUserId != params.row.createUserId &&this.loginId != this.Common.admin) && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                        &&(sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined)? '#d0d0d0':'red',
                                        pointerEvents:  (this.currentUserId != params.row.createUserId&&this.loginId !=this.Common.admin)  && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)
                                        &&(sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) == undefined)? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    planName: [{required: true, message: '  ', trigger: 'blur,change'}],
                    planDate: [{required: true, message: '  ', trigger: 'blur,change', pattern: /.+/ }],
                    screenOrgId: [{required: true, message: '  ', trigger: 'blur'}],
                    screenPositionId: [{required: true, message: '  ', trigger: 'blur'}]
                },
                selectModelModal: false,
                currentScreenOrgId: '',
                currentScreenOrgName: '',
                dataTable: [],
                screenUsers:[],
                screenUserIds:[],
                model1: false,
                model3: false,
                lastDaysDisabled: true,
                add: false,
                loading: false,
                tableHeight: '',
                deleteRows: [],
                buttonLoading: false,
                viewModal: false,
                viewForm: {},
                viewSpanShow: false,
                viewCheckCycleRadio: '',
                viewCheckCycleCheckbox: [],
                setCurrentScreenPositionName: {},
                ifHoliday: false,
            }
        },
        mounted: function () {
            this.currentUserId = sessionStorage('userId').getObject('userId').userId;
            this.loginId = sessionStorage('userId').getObject('userId').loginId;
            this.companyId = sessionStorage('userId').getObject('userId').companyId;
            this.rootOrgId =  sessionStorage('userId').getObject('userId').companyId;
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.getHoliday();
            this.query();
        },
        methods: {
            switchQuery(flag){
                this.switchFlag = flag;
                if(this.switchFlag) {
                    this.tableHeight = this.tableHeight - 74;
                }else{
                    this.tableHeight = this.tableHeight + 74;
                }
            },
            setOrgInfo(data){
                this.form1.screenOrgId = data[data.length - 1];
            },
            setScreenPositionId(data) {
                this.form1.screenPositionId = data[data.length - 1];
            },
            cycleChange(value){
                if (value == '1') {
                    this.lastDayLabel = "不填写默认为12月31日前均可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '年度排查计划'
                } else if (value == '2') {
                    this.lastDayLabel = "不填写默认为任务当天可执行";
                   this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '每天排查计划'
                } else if (value == '3') {
                    this.lastDayLabel = "不填写默认为任务当天可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '工作日排查计划'
                }  else if (value == '5') {
                    this.lastDayLabel = "不填写默认为任务当天可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '自定义排查计划'
                } else if (value == '8') {
                    this.lastDayLabel = "不填写默认为下一次任务前均可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '双周排查计划'
                } else if (value == '6') {
                    this.lastDayLabel = "不填写默认为当月可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '月度排查计划'
                } else if (value == '7') {
                    this.lastDayLabel = "不填写默认为当季可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '季度排查计划'
                } else if (value == '4') {
                    this.lastDayLabel = "不填写默认为1-6月或7-12月可执行";
                    this.dataForm.planName = this.dataForm.screenOrgName + this.dataForm.screenPositionName + '半年排查计划'
                }
            },
            getSelectModelData(row) {
                row.checked = true;
                this.screenUsers.append(row);
            },
            getSelectModelData(row) {
                this.dataForm.screenPositionId = row.postId;
                this.dataForm.screenPositionName = row.postName;
                this.dataForm.itemPlanId = row.id;
                this.dataForm.screenOrgName = row.proName;
                this.cycleChange(this.viewCheckCycleRadio)
                this.selectModelModal = false;
                this.dataForm.screenUserId="";
            },
            openModelModal() {
                this.selectModelModal = true;
            },
            handleCancel() {
                this.model1 = false;
            },
            saveMultiModify(){
              this.buttonLoading = true;
              var dateForm = {};
              if(this.planDate.length!=0){
                if(this.planDate[0] != '' && this.planDate[1] != ''){
                  dateForm.startDate = this.formatDate(new Date(this.planDate[0]), 'yyyy-MM-dd');
                  dateForm.endDate = this.formatDate(new Date(this.planDate[1]), 'yyyy-MM-dd');
                }
              }
              dateForm.planIds = this.multiModifyPlanIds;
              this.$http.get(Api.apsgPlanMultiModify, {params: dateForm}).then((res) => {
                if(res.data.result == 'fail'){
                  this.$Message.error("数据保存失败")
                }else{
                  this.$Message.success("保存成功")
                }
                this.model3 = false;
                this.query();
                this.buttonLoading = false
              }).catch(e => {
                this.model3 = false;
                this.query();
                this.buttonLoading = false
                this.$Message.error("数据保存失败")
              })
            },
            handleCanleMultiModify(){
                this.model3 = false;
            },
            addInfo() {
                this.modalTitle="排查计划新增"
                this.planTypeEnable = false;
                this.planDate = [];
                this.dataForm = {
                    screenPositionId:'',
                    itemPlanId:'',
                    screenPositionName:'',
                    planName:'',
                    startDate:'',
                    endDate:'',
                    planType:'0',
                    distributeType:'0'
                };
                this.screenUserIds=[];
                this.screenUsers=[];
                this.viewCheckCycleRadio = '2';
                this.currentScreenOrgId = '';
                this.currentScreenOrgName = '';
                this.setCurrentScreenPositionName = {};
                this.model1 = true;
            },
            exportFile(){
                let data = {
                    planName: this.form1.planName,
                    checkCycle: this.form1.checkCycle,
                    screenPositionName:this.form1.screenPositionName,
                    orgId:sessionStorage('userId').getObject('userId').companyId
                };
                if(this.form1.screenOrgId != ""){
                    data.orgId = this.form1.screenOrgId;
                }
                this.$http.get(Api.apsgPlanExcport,{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "排查计划("+ this.formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                })
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            async toEdit(params) {
                this.screenUserIds=[];
                this.screenUsers=[];
                await this.$http.get(Api.getUserByIds + "?ids=" + params.row.screenUserId).then((res) => {
                    if(res.data.result != "fail"){
                        this.screenUsers = res.data.data;
                    }
                })
                if(params.row.screenUserId != null)
                    this.screenUserIds = params.row.screenUserId.split(",");
                this.modalTitle = "排查计划修改"
                this.viewCheckCycleCheckbox = [];
                this.model1 = true;
                this.dataForm = params.row;
                if(params.row.screenUserId != null && params.row.screenUserId != '')
                    this.dataForm.distributeType = '1';
                else
                    this.dataForm.distributeType = '0';
                this.dataForm.startDate = this.formatDate(new Date(this.dataForm.startDate), 'yyyy-MM-dd');
                this.dataForm.endDate = this.formatDate(new Date(this.dataForm.endDate), 'yyyy-MM-dd');
                this.planDate = [this.dataForm.startDate,this.dataForm.endDate];
                let checkCycle = params.row.checkCycle.split(",");
                this.viewCheckCycleRadio = params.row.checkCycle[0];
                if (checkCycle.length > 1) {
                    this.viewSpanShow = true;
                    for (let i = 1; i < checkCycle.length; i++) {
                        this.viewCheckCycleCheckbox.push(checkCycle[i]);
                    }
                }
                this.currentScreenOrgName = params.row.screenOrgName;
                this.currentScreenOrgId = params.row.screenOrgId;
            },
            async viewData(params) {
                this.screenUserIds=[];
                this.screenUsers=[];
                this.viewForm = params.row;
                this.viewForm.createDateStr = this.formatDate(new Date(this.viewForm.createDate), 'yyyy-MM-dd');
                if(this.viewForm.screenUserId != null && this.viewForm.screenUserId != '')
                    this.viewForm.distributeType = '1';
                else
                    this.viewForm.distributeType = '0';
                this.viewForm.screenUserName = "";
                await this.$http.get(Api.getUserByIds + "?ids=" + this.viewForm.screenUserId).then((res) => {
                    if(res.data.result != "fail"){
                        let users = res.data.data;
                        for(var i=0;i<users.length;i++){
                            if(this.viewForm.screenUserName == "")
                                this.viewForm.screenUserName += users[i].userName
                            else
                                this.viewForm.screenUserName += "," + users[i].userName
                        }
                    }
                })
                this.viewCheckCycleCheckbox = [];
                this.viewForm.startDate = this.formatDate(new Date(this.viewForm.startDate), 'yyyy-MM-dd');
                this.viewForm.endDate = this.formatDate(new Date(this.viewForm.endDate), 'yyyy-MM-dd');
                if(params.row.screenUserId != null)
                    this.screenUserIds = params.row.screenUserId.split(",");
                let checkCycle = params.row.checkCycle.split(",");
                this.viewCheckCycleRadio = params.row.checkCycle[0];
                if (checkCycle.length > 1) {
                    this.viewSpanShow = true;
                    for (let i = 1; i < checkCycle.length; i++) {
                        this.viewCheckCycleCheckbox.push(checkCycle[i]);
                    }
                }
                this.viewModal = true;
            },
            saveData() {
                this.$refs.dataForm.validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true;
                        if(this.planDate.length!=0){
                            if(this.planDate[0] != '' && this.planDate[1] != ''){
                                this.dataForm.startDate = this.formatDate(new Date(this.planDate[0]), 'yyyy-MM-dd');
                                this.dataForm.endDate = this.formatDate(new Date(this.planDate[1]), 'yyyy-MM-dd');
                            }
                        }
                        this.dataForm.screenUserId = "";
                        for (let i = 0; i < this.screenUserIds.length; i++) {
                            this.dataForm.screenUserId += this.screenUserIds[i];
                            if (i != this.screenUserIds.length - 1) this.dataForm.screenUserId += ",";
                        }
                        let formData = this.dataForm;
                        let checkCycle = this.viewCheckCycleRadio;
                        let viewCheckCycleCheckbox = this.viewCheckCycleCheckbox;
                        if (viewCheckCycleCheckbox.length > 0) {
                            checkCycle += ",";
                            for (let i = 0; i < viewCheckCycleCheckbox.length; i++) {
                                checkCycle += viewCheckCycleCheckbox[i];
                                if (i != viewCheckCycleCheckbox.length - 1) checkCycle += ",";
                            }
                        }
                        if(checkCycle == 5){
                            if(viewCheckCycleCheckbox.length == 0){
                                this.$Message.error("请自选择定义天数！");
                                this.buttonLoading = false;
                                return false;
                            }
                        }
                        formData.checkCycle = checkCycle;
                        this.$http.post(Api.saveOrUpdateApsgPlan, formData).then((res) => {
                            if(res.data.result == 'fail'){
                                this.$Message.error("数据保存失败")
                            }else{
                                this.$Message.success("保存成功")
                            }
                            this.model1 = false;
                            this.query();
                            this.buttonLoading = false
                        }).catch(e => {
                            this.model1 = false;
                            this.query();
                            this.buttonLoading = false
                            this.$Message.error("数据保存失败")
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            query() {
                this.loading = true;
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    planName: this.form1.planName,
                    companyName: this.form1.companyName,
                    checkCycle: this.form1.checkCycle,
                    screenPositionName:this.form1.screenPositionName,
                    orgId:sessionStorage('userId').getObject('userId').companyId,
                    twoLevelOrgId: this.form1.twoLevelOrgId,
                    key: this.form1.key,
                    order: this.form1.order
                };
                if(this.form1.screenOrgId != ""){
                    data.orgId = this.form1.screenOrgId;
                }
                let url = Api.getPlanDataList;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            choosePeople(){
                this.apsgPlanUserForSelectModal = true;
                this.$refs.apsgPlanUserSelect.query();
            },
            reset() {
                this.form1 = {planName:"",screenPositionId:'',screenOrgId:'',checkCycle:''};
                this.query();
            },
            deleteData(params) {
                let _this = this;
                let config = {
                    title: '系统提示',
                    content: '确认删除选中数据吗?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: function () {
                        _this.$Spin.show({
                            render: (h) => {
                                return h('div', [
                                    h('Icon', {
                                        'class': 'demo-spin-icon-load',
                                        props: {
                                            type: 'ios-loading',
                                            size: 18
                                        }
                                    }),
                                    h('div', 'Loading')
                                ])
                            }
                        });
                        let url = Api.deleteApsgPlanById + '/' + params.row.planId;
                        this.$http.delete(url).then((res) => {
                            _this.$Message.success('删除成功');
                            _this.query();
                            _this.$Spin.hide();
                        }).catch(e => {
                            _this.$Spin.hide();
                            _this.$Message.error('删除失败' + e);
                        })
                    },
                    onCancel: function () {
                    }
                }
                this.$Modal.confirm(config);
            },
            closeModel() {
                this.apsgPlanUserForSelectModal = false;
            },
            getSelectData(users){
                this.screenUsers = this.unique(this.screenUsers.concat(users));
                this.screenUserIds = [];
                this.screenUsers.forEach(item=>{
                    this.screenUserIds.push(item.userId);
                })
                if(this.screenUserIds.length > 0){
                    this.planTypeEnable = true;
                }
                this.apsgPlanUserForSelectModal = false;
            },
            unique(arr) {
                const res = new Map();
                return arr.filter((arr) => !res.has(arr.userId) && res.set(arr.userId, 1));
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            multiModify(){
              let data = this.$refs.table.getSelection();
              if(data.length === 0){
                this.$Message.error("请至少选择一条记录！");
                return;
              }
              this.multiModifyPlanIds = "";
              data.forEach(item => {
                this.multiModifyPlanIds += item.planId + ",";
              });
              this.planDate = [];
              this.model3 = true;
            },
            delayInfo(){
                let data = this.$refs.table.getSelection();
                if(data.length === 0){
                    this.$Message.error("请至少选择一条记录！");
                    return;
                }
                let errorText = "";
                let planIds = "";
                data.forEach(item => {
                    let nowYear = new Date().getFullYear();
                    let endYear = new Date(item.endDate).getFullYear();
                    if(nowYear != endYear){
                        errorText += item.planName + ";"
                    }
                    planIds += item.planId + ",";
                });
                if(errorText!= ""){
                    this.$Notice.error({
                        title: '请选择本年度排查计划，以下排查计划结束日期有误：',
                        desc: errorText.substring(0, errorText.length-1)
                    });
                    return;
                }
                let _this = this;
                let config = {
                    title: '系统提示',
                    content: '确认延期选中数据吗?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: function () {
                        let url = Api.apsgPlanDelay;
                        let queryParams = {
                            planIds: planIds, endDate: (new Date().getFullYear() +1) + '-12-31'
                        }
                        this.loading = true;
                        this.$http.get(url, {params: queryParams}).then((res) => {
                            if(res.data.result == 'fail'){
                                _this.$Message.error("延期失败")
                            }else{
                                _this.$Message.success("延期成功")
                                _this.query();
                            }
                        }).catch(e => {
                            _this.$Message.error("数据获取失败")
                        })
                    },
                    onCancel: function () {
                    }
                }
                this.$Modal.confirm(config);
            },
            batchDelete(){
                let data = this.$refs.table.getSelection();
                if(data.length === 0){
                    this.$Message.error("请至少选择一条记录！");
                    return;
                }
                let planIds = "";
                data.forEach(item => {
                    planIds += item.planId + ",";
                });
                let _this = this;
                let config = {
                    title: '系统提示',
                    content: '确认删除选中数据吗?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: function () {
                        _this.$Spin.show({
                            render: (h) => {
                                return h('div', [
                                    h('Icon', {
                                        'class': 'demo-spin-icon-load',
                                        props: {
                                            type: 'ios-loading',
                                            size: 18
                                        }
                                    }),
                                    h('div', 'Loading')
                                ])
                            }
                        });
                        let url = Api.apsgPlanDeleteBatch;
                        this.$http.delete(url, {params: {planIds: planIds}}).then((res) => {
                            _this.$Message.success('删除成功');
                            _this.query();
                            _this.$Spin.hide();
                        }).catch(e => {
                            _this.$Spin.hide();
                            _this.$Message.error('删除失败' + e);
                        })
                    },
                    onCancel: function () {
                    }
                }
                this.$Modal.confirm(config);
            },
            getHoliday(){
                this.$http.post(Api.queryYearHoliday, {conditions: {year: new Date().getFullYear() +1}, startPage: 1, size: 10}).then((res) => {
                    if(res.data.data.totalSize >= 1){
                        this.ifHoliday = true;
                        this.startDateOption = {
                            disabledDate(date) {
                                return (date && date.valueOf() < Date.now() - 86400000) || new Date((new Date().getFullYear() + 1) + '-12-31').valueOf() <  date.valueOf();
                            }
                        }
                    }
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            querySort({column, key, order}){
              this.form1.key = key;
              this.form1.order = order;
              this.query();
            }
        },
        watch: {
            'viewCheckCycleRadio': function (val) {
                if (val == '5') {
                    this.viewSpanShow = true;
                } else {
                    this.viewCheckCycleCheckbox = [];
                    this.viewSpanShow = false;
                }

                if (val == '2' || val == '3') {
                    this.dataForm.lastDays = '';
                    this.lastDaysDisabled = true;
                } else {
                    this.lastDaysDisabled = false;
                }
            },
        }
    }
</script>
<style lang='css'>
    @import './../../../index.css';
</style>
